package com.yhao.controller;

import com.yhao.Dao.LoginRepository;
import com.yhao.bean.UploadResult;
import com.yhao.bean.login.LoginBean;
import com.yhao.service.LoginService;
import com.yhao.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.MultipartConfigElement;
import java.io.File;
import java.nio.file.Paths;
import java.util.Date;

@RestController
public class StudentController {

    private Logger log = LoggerFactory.getLogger(StudentController.class);
    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private LoginService loginService;

    @Autowired
    private LoginRepository loginDao;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.http.multipart.location}")
    private String filePath;

    //根据token上传头像
    @Transactional
    @PostMapping(value = "uploadImg")
    public UploadResult upload(@RequestParam("file") MultipartFile file,
                               @RequestParam(value = "token", required = true) String token) {
        UploadResult uploadResult = new UploadResult();
        if (file.isEmpty()) {
            uploadResult.setMassage("upload failed,file is null!");
            uploadResult.setCode(-1);
            return uploadResult;
        }
        if (StringUtils.isEmpty(token)) {
            uploadResult.setMassage("get token failed!");
            uploadResult.setCode(-1);
            return uploadResult;
        }
        String userName = TokenUtil.getUserNameFromToken(token, redisTemplate);
        if (StringUtils.isEmpty(userName)) {
            uploadResult.setMassage("token is illegal!");
            uploadResult.setCode(-1);
            return uploadResult;
        }
        // 获取文件名(包括后缀)
        String fileName = file.getOriginalFilename();
        //获取文件格式失败
        if (!fileName.contains(".")) {
            uploadResult.setMassage("file format error");
            uploadResult.setCode(-1);
            return uploadResult;
        }

        //文件名只包含英文字母，数字，下划线和 .
        if (!fileName.matches("[0-9A-Za-z_.]*")) {
            // 获取文件的后缀名(包括 . )
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            // 解决中文问题，liunx下中文路径，图片显示问题
            fileName = new Date().getTime() + suffixName;
        }
        // 文件上传后的路径
//        String filePath = "E://test//";
        String filePath = "/home/img/";

        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            LoginBean loginBean = loginDao.findByUserName(userName);
            loginBean.setImg("http://59.110.234.50:8080/img/" + fileName);
            loginDao.saveAndFlush(loginBean);
            uploadResult.setImgUrl("http://59.110.234.50:8080/img/" + fileName);
            uploadResult.setMassage("upload success!");
            uploadResult.setCode(1);
            return uploadResult;
        } catch (Exception e) {
            e.printStackTrace();
            uploadResult.setMassage("upload failed," + e.getMessage());
            uploadResult.setCode(-1);
        }
        return uploadResult;
    }

    //获取头像地址

    /**
     * @param filename
     * @return ResponseEntity<?>    返回类型
     * @Title: getFile
     */
    @GetMapping("/img/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(filePath + filename)));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }


}
